public class ReverseKGroup {
    // leetcode k个一组翻转链表
    // https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        ListNode cur = head;
        for (int i = 0; i < k; i++) {
            if (cur == null) return head;
            cur = cur.next;
        }
        ListNode next = reverseKGroup(cur, k);
        ListNode prev = next, cur1 = head;
        for (int i = 0; i < k; i++) {
            ListNode nextCur = cur1.next;
            cur1.next = prev;
            prev = cur1;
            cur1 = nextCur;
        }
        return prev;
    }

    public static void main(String[] args) {
        ReverseKGroup reverseKGroup = new ReverseKGroup();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        reverseKGroup.reverseKGroup(head, 2);
    }
}
